<template>
  <div class="main">
    <a-form 
      class="user-layout-login" 
      autocomplete="off" 
      :model="formState" 
      @finish="handleSubmit">
      <a-tabs :activeKey="formState.customActiveKey" centered :tabBarStyle="{ textAlign: 'center', borderBottom: 'unset' }"
        @change="handleTabClick">
        <a-tab-pane key="tab1" :tab="$t('user.login.tab-login-credentials')">
          <a-alert v-if="formState.isLoginError" type="error" showIcon style="margin-bottom: 24px;"
            :message="$t('user.login.message-invalid-credentials')" />
          <a-form-item name="username"
            :rules="[{ required: true, message: $t('user.userName.required'), trigger: 'change' }]">
            <a-input size="large" type="text" :placeholder="$t('user.login.username.placeholder')"
              v-model:value="formState.username">
              <template #prefix>
                <user-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input>
          </a-form-item>

          <a-form-item name="password"
            :rules="[{ required: true, message: $t('user.password.required'), trigger: 'blur' }]">
            <a-input-password size="large" :placeholder="$t('user.login.password.placeholder')"
              v-model:value="formState.password">
              <template #prefix>
                <lock-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input-password>
          </a-form-item>
        </a-tab-pane>
        <a-tab-pane key="tab2" :tab="$t('user.login.tab-login-mobile')">
          <a-form-item name="mobile"
            :rules="[{ required: true, pattern: /^1[34578]\d{9}$/, message: $t('user.login.mobile.placeholder'), trigger: 'change' }]">
            <a-input size="large" type="text" :placeholder="$t('user.login.mobile.placeholder')"
              v-model:value="formState.mobile">
              <template #prefix>
                <mobile-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
              </template>
            </a-input>
          </a-form-item>

          <a-row :gutter="16">
            <a-col class="gutter-row" :span="16">
              <a-form-item name="captcha"
                :rules="[{ required: true, message: $t('user.verification-code.required'), trigger: 'blur' }]">
                <a-input size="large" type="text" :placeholder="$t('user.login.mobile.verification-code.placeholder')"
                  v-model:value="formState.captcha">
                  <template #prefix>
                    <mail-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
                  </template>
                </a-input>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="8">
              <a-button class="getCaptcha" tabindex="-1" :disabled="formState.state.smsSendBtn"
                @click.stop.prevent="getCaptcha"
                v-text="!formState.state.smsSendBtn && $t('user.register.get-verification-code') || (formState.state.time + ' s')"></a-button>
            </a-col>
          </a-row>
        </a-tab-pane>
      </a-tabs>

      <a-form-item>
        <a-checkbox>{{ $t('user.login.remember-me')
        }}</a-checkbox>
        <router-link :to="{ name: 'recover' }" class="forge-password" style="float: right;">{{
          $t('user.login.forgot-password') }}</router-link>
      </a-form-item>

      <a-form-item style="margin-top:24px">
        <a-button size="large" type="primary" htmlType="submit" class="login-button" :loading="formState.state.loginBtn"
          :disabled="formState.state.loginBtn">{{ $t('user.login.login') }}</a-button>
      </a-form-item>

      <div class="user-login-other">
        <span>{{ $t('user.login.sign-in-with') }}</span>
        <a>
          <AlipayCircleOutlined class="item-icon" />
        </a>
        <a>
          <TaobaoCircleOutlined class="item-icon" />
        </a>
        <a>
          <WeiboCircleOutlined class="item-icon" />
        </a>
        <router-link class="register" :to="{ name: 'register' }">{{ $t('user.login.signup') }}</router-link>
      </div>
    </a-form>

    <!-- <two-step-captcha v-if="requiredTwoStepCaptcha" :visible="stepCaptchaVisible" @success="stepCaptchaSuccess"
      @cancel="stepCaptchaCancel"></two-step-captcha> -->
  </div>
</template>

<script setup>
import md5 from 'md5'
import { reactive } from "vue"
import { notification } from 'ant-design-vue';
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha.vue'
import useUserStore from '@/store/user.js'
import { useRouter } from 'vue-router';
import { timeFix } from '@/utils/util'
import { getSmsCaptcha, get2step } from '@/api/login'
import { AlipayCircleOutlined, TaobaoCircleOutlined, WeiboCircleOutlined, UserOutlined, LockOutlined, MobileOutlined, MailOutlined } from '@ant-design/icons-vue';
const formState = reactive({
  customActiveKey: 'tab1',
  loginBtn: false,
  // login type: 0 email, 1 username, 2 telephone
  loginType: 0,
  username: "",
  password: "",
  mobile: "",
  captcha: "",
  isLoginError: false,
  requiredTwoStepCaptcha: false,
  stepCaptchaVisible: true,
  state: {
    time: 60,
    loginBtn: false,
    // login type: 0 email, 1 username, 2 telephone
    loginType: 1,
    smsSendBtn: false
  }
});
const UserStore = useUserStore();
const router = useRouter();
const { Login, Logout } = UserStore;
const handleUsernameOrEmail = (rule, value, callback) => {
  // const { state } = this
  // const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
  // if (regex.test(value)) {
  //   state.loginType = 0
  // } else {
  //   state.loginType = 1
  // }
  // callback()
};
const handleTabClick = (key) => {
  formState.customActiveKey = key
  // this.form.resetFields()
};
const handleSubmit = (values) => {
  formState.state.loginBtn = true
  try {
    console.log(values)
    const loginParams = { ...values }
          delete loginParams.username
          loginParams[!formState.state.loginType ? 'email' : 'username'] = values.username
          loginParams.password = md5(values.password);
          Login(loginParams)
            .then((res) => loginSuccess(res))
            .catch(err => requestFailed(err))
            .finally(() => {
              formState.state.loginBtn = false
            })

  } catch (error) {

  }
};
const getCaptcha = (e) => {
  e.preventDefault()
  // const { form: { validateFields }, state } = this

  // validateFields(['mobile'], { force: true }, (err, values) => {
  //   if (!err) {
  //     state.smsSendBtn = true

  //     const interval = window.setInterval(() => {
  //       if (state.time-- <= 0) {
  //         state.time = 60
  //         state.smsSendBtn = false
  //         window.clearInterval(interval)
  //       }
  //     }, 1000)

  //     const hide = this.$message.loading('验证码发送中..', 0)
  //     getSmsCaptcha({ mobile: values.mobile }).then(res => {
  //       setTimeout(hide, 2500)
  //       this.$notification['success']({
  //         message: '提示',
  //         description: '验证码获取成功，您的验证码为：' + res.result.captcha,
  //         duration: 8
  //       })
  //     }).catch(err => {
  //       setTimeout(hide, 1)
  //       clearInterval(interval)
  //       state.time = 60
  //       state.smsSendBtn = false
  //       this.requestFailed(err)
  //     })
  //   }
  // })
};
const stepCaptchaSuccess = () => {
  this.loginSuccess()
};
const stepCaptchaCancel = () => {
  // this.Logout().then(() => {
  //   this.loginBtn = false
  //   this.stepCaptchaVisible = false
  // })
};
const loginSuccess = () => {
  // check res.homePage define, set $router.push name res.homePage
  // Why not enter onComplete
  /*
  this.$router.push({ name: 'analysis' }, () => {
    console.log('onComplete')
    this.$notification.success({
      message: '欢迎',
      description: `${timeFix()}，欢迎回来`
    })
  })
  */
  router.push({ path: '/dashboard/workplace' })
  // 延迟 1 秒显示欢迎信息
  setTimeout(() => {
    notification.success({
      message: '欢迎',
      description: `${timeFix()}，欢迎回来`
    })
  }, 1000)
  formState.isLoginError = false
};
const requestFailed = (err) => {
  formState.isLoginError = true
  notification.error({
    message: '错误',
    description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
    duration: 4
  })
}

</script>

<style lang="less" scoped>
.user-layout-login {
  label {
    font-size: 14px;
  }

  .getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
  }

  .forge-password {
    font-size: 14px;
  }

  button.login-button {
    padding: 0 15px;
    font-size: 16px;
    height: 40px;
    width: 100%;
  }

  .user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;

    .item-icon {
      font-size: 24px;
      color: rgba(0, 0, 0, 0.2);
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: #1890ff;
      }
    }

    .register {
      float: right;
    }
  }
}</style>
